package mysql

import (
	"log"
	"reflect"
	"strconv"
)

type DeviceSlotStateMapper struct {
	ds *DataMysqlSourceClinet
}
type DeviceSlotState struct {
	DeviceId int64 `db:"device_id"`
	SlotId   int64 `db:"slot_id"`
	Useable  int64 `db:"useable"'`
	State    int64 `db:"state"`
	Battery  int64 `db:"battery"`
}

func (dbf *DeviceSlotState) ToDbTagStr(Idexclude bool) string {
	of := reflect.ValueOf(dbf).Elem()
	var result = ""
	num := of.NumField()
	for i := 0; i < num; i++ {
		if Idexclude && i == 0 {
			continue
		}
		field := of.Type().Field(i)
		tag := field.Tag
		result = result + tag.Get("db") + ","
	}
	return result[0 : len(result)-1]
}

func (dbm *DeviceSlotStateMapper) QueryByDeviceId(deviceId int64) ([] DeviceSlotState) {
	sql := buildDeviceSlotStateQuerySQL(strconv.FormatInt(deviceId, 10))
	return dbm.normalDeviceBaseInfoQuery2(sql)
}

func (dbm *DeviceSlotStateMapper) normalDeviceBaseInfoQuery2(sql string) ([] DeviceSlotState) {
	var slotStates [] DeviceSlotState
	e := dbm.ds.SqlDB.Select(&slotStates, sql)
	if e != nil {
		log.Println("查询失败！", e)
		return nil
	}
	if len(slotStates) == 0 {
		log.Println("设备不存在！")
		return nil
	}
	return slotStates
}

func buildDeviceSlotStateQuerySQL(vle string) string {
	var normalSql = "SELECT " + (&DeviceSlotState{}).ToDbTagStr(false) + " FROM device_slot_state WHERE device_id = "
	return normalSql + vle
}

func NewDeviceSlotMapper(ds *DataMysqlSourceClinet) (*DeviceSlotStateMapper) {
	mapper := &DeviceSlotStateMapper{}
	mapper.ds = ds
	return mapper
}
